package com.laxia.util;

import com.alibaba.excel.util.CollectionUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.poifs.filesystem.DirectoryEntry;
import org.apache.poi.poifs.filesystem.DocumentEntry;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayInputStream;
import java.util.Map;

/**
 * word 导出工具
 *
 * @author weishuai
 * @version 1.0
 * @date 2019-03-27 15:33
 */
@Slf4j
public class WordUtil {

    /**
     * 导出word文件
     *
     * @param fileName
     * @param ueditorContent word的富文本内容
     * @param paramMap       word的富文本内容替换变量的参数
     */
    public static void exportByUeditorContent(String fileName, String ueditorContent, Map<String, Object> paramMap) {
        HttpServletRequest request = SessionUtil.getCurrentRequest();
        HttpServletResponse response = SessionUtil.getCurrentResponse();
        try {
            fileName = StringUtil.encode(fileName);
            //如果变量不为空，用参数替换占位符变量
            if (!CollectionUtils.isEmpty(paramMap)) {
                //todo  freemark 变量替换
            }

            ueditorContent = StringUtil.encode(ueditorContent);
            //这里是必须要设置编码的，不然导出中文就会乱码。
            byte b[] = ueditorContent.getBytes("utf-8");
            //将字节数组包装到流中
            ByteArrayInputStream bais = new ByteArrayInputStream(b);

            POIFSFileSystem poifs = new POIFSFileSystem();
            DirectoryEntry directory = poifs.getRoot();
            DocumentEntry documentEntry = directory.createDocument("WordDocument", bais);
            //导出word格式
            response.setCharacterEncoding("utf-8");
            response.setContentType("application/msword");

            response.addHeader("Content-Disposition", "attachment;filename=" + fileName + ".doc");
            ServletOutputStream ostream = response.getOutputStream();
            poifs.writeFilesystem(ostream);
            bais.close();
            ostream.flush();
            ostream.close();
            poifs.close();
        } catch (Exception e) {
            log.error("导出word异常,fileName:{},content:{}", fileName, ueditorContent);
        }


    }


}
